#include "EmotivDataCollector.h"

namespace EEGSignalProcessor
{
	EmotivDataCollector::EmotivDataCollector(void)
		: DataCollector()
	{
		_channel = ED_F3;
		_eventHandle = EE_EmoEngineEventCreate();
		_eState = EE_EmoStateCreate();
		_dataHandle = EE_DataCreate();
	EE_DataSetBufferSizeInSec((float)TIME_BUFFER_SIZE / 128.0);//collects at 128 hz

		_canCollect = false;
		_userID = 0;

		if (EE_EngineConnect() != EDK_OK)
		{
			throw std::exception("Could not connect to headset!");
		}
	}

	EmotivDataCollector::~EmotivDataCollector(void) 
	{
		//disconnect from system
		EE_EngineDisconnect();
		EE_EmoStateFree(_eState);
		EE_EmoEngineEventFree(_eventHandle);
	}

	void EmotivDataCollector::UpdateData()
	{
		_state = EE_EngineGetNextEvent(_eventHandle);

		//check user added
		if (_state == EDK_OK)
		{
			EE_Event_t eventType = EE_EmoEngineEventGetType(_eventHandle);

			if (eventType == EE_UserAdded)
			{
				EE_DataAcquisitionEnable(_userID, true);
				_canCollect = true;
			}
		}

		if (_canCollect)
		{
			EE_DataUpdateHandle(0, _dataHandle);

			unsigned int nSamplesTaken=0;
			EE_DataGetNumberOfSample(_dataHandle,&nSamplesTaken);

			if (nSamplesTaken != 0) {
				double* data = new double[nSamplesTaken];
				EE_DataGet(_dataHandle, _channel, data, nSamplesTaken);
				for (int i = 0; i < (int) nSamplesTaken; i++)
				{
					_dataBuffer[(_currentIndex + i) % TIME_BUFFER_SIZE] = data[i];
				}
				_currentIndex = (_currentIndex + nSamplesTaken) % TIME_BUFFER_SIZE;
				delete[] data;
			}
		}
	}

	void EmotivDataCollector::SetChannel(EE_DataChannel_t newChannel)
	{
		_channel = newChannel;
	}
}
